package cn.anc.httpcontrolutil;

import android.app.Activity;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by baobaoding on 2017/5/6.
 */

public class HttpFileDownload extends Thread {
    private static String TAG = HttpFileDownload.class.getSimpleName();
    private OkHttpClient mOkHttpClient = new OkHttpClient();
    private String remote_url = null;
    private String local_path = null;
    private HttpFileDownloadListener listener = null;
    private Activity activity = null;

    public interface HttpFileDownloadListener {
        void OnEvent(int eventCode);
        void OnDownloadProgress(int progress);
    }

    public static class HttpFileDownloadEvent {
        public static final int HTTP_FILE_DOWNLOAD_START = 0;
        public static final int HTTP_FILE_DOWNLOAD_SUCCESS = 1;
        public static final int HTTP_FILE_DOWNLOAD_FAIL = 2;
    }

    public HttpFileDownload(Activity _activity, String _remote_url, String _local_path) {
        activity = _activity;
        remote_url = _remote_url;
        local_path = _local_path;
    }

    public HttpFileDownload(Activity _activity, String _remote_url, String _local_path, HttpFileDownloadListener _listener) {
        activity = _activity;
        remote_url = _remote_url;
        local_path = _local_path;
        listener = _listener;
    }

    private void guiOnEvent(final int eventCode) {
        if (listener != null && activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listener.OnEvent(eventCode);
                }
            });
        }
    }

    private void guiOnProgress(final int progress) {
        if (listener != null && activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    listener.OnDownloadProgress(progress);
                }
            });
        }
    }

    @Override
    public void run() {
        super.run();
        try {
            Request request = new Request.Builder().url(remote_url).build();
            guiOnEvent(HttpFileDownloadEvent.HTTP_FILE_DOWNLOAD_START);
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    guiOnEvent(HttpFileDownloadEvent.HTTP_FILE_DOWNLOAD_FAIL);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    byte[] buf = new byte[64 * 1024];
                    FileOutputStream fos = null;
                    InputStream is = null;
                    int len = 0;
                    try {
                        is = response.body().byteStream();
                        long total = response.body().contentLength();
                        File file = new File(local_path);
                        fos = new FileOutputStream(file);
                        long sum = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            sum += len;
                            //Log.d(TAG, "onResponse: read len:" + len + ",sum len:" + sum + ",total len:" + total);
                            guiOnProgress((int) (sum * 1.0f / total * 100));
                        }
                        fos.flush();
                        Log.d(TAG, "文件下载成功");
                        guiOnEvent(HttpFileDownloadEvent.HTTP_FILE_DOWNLOAD_SUCCESS);
                    } catch (Exception e) {
                        Log.d(TAG, "文件下载失败");
                        guiOnEvent(HttpFileDownloadEvent.HTTP_FILE_DOWNLOAD_FAIL);
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {

                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {

                        }
                    }
                }
            });
        } catch (Exception ex) {
            Log.e(TAG, "download: " + ex.getMessage());
            guiOnEvent(HttpFileDownloadEvent.HTTP_FILE_DOWNLOAD_FAIL);
        }
    }
}
